package com.yxx.task;

import com.alibaba.druid.support.json.JSONUtils;
import com.sun.media.jfxmedia.logging.Logger;
import com.yxx.mapper.OrderMapper;
import com.yxx.medicinepojo.entity.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类，定时处理订单状态
 * @author yuxiangxun
 * @date 2024/9/28
 * @apiNote
 */
@Slf4j
@Component
public class OrderTask {

    private static final String CANCEL_REASON = "订单超时，自动取消";

    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "1/5 * * * * ?")
    public void processTimeoutOrder(){
        log.info("定时处理超时订单：{}", LocalDateTime.now());

        //设置当前时间-15分钟
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        //获取超时订单  付款状态后超过15分钟的订单
        Integer status  = Orders.PENDING_PAYMENT;
        List<Orders> timeOutOrdersList = orderMapper.getOrdersByStatusAndOrderTimeLessTime(status,time);

        //待付款的订单超时啦
        if(!CollectionUtils.isEmpty(timeOutOrdersList) && timeOutOrdersList.size() > 0){
            for(Orders timeOutOrder : timeOutOrdersList){
                timeOutOrder.setStatus(Orders.CANCELLED);
                timeOutOrder.setCancelReason(CANCEL_REASON);
                timeOutOrder.setCancelTime(LocalDateTime.now());

                orderMapper.update(timeOutOrder);
            }
        }
    }

    /**
     * 处理状态一直处于派送中的订单 (派送中 -> 已完成)
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void processDeliveryOrder(){
        log.info("定时处理状态处于派送中的订单：{}",LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(60);

        Integer status = Orders.DELIVERY_IN_PROGRESS;

        List<Orders> successOrdersList = orderMapper.getOrdersByStatusAndOrderTimeLessTime(status, time);

        if(!CollectionUtils.isEmpty(successOrdersList) && successOrdersList.size() > 0){
            for(Orders successOrder : successOrdersList){
                successOrder.setStatus(Orders.COMPLETED);
                orderMapper.update(successOrder);
            }
        }
    }
}
